<template>
  <div class="search-result-container">
    <!-- 点击实现后退效果 -->
    <van-nav-bar
      title="搜索结果"
      left-arrow
      @click-left="$router.go(-1)"
      fixed
    />
    <!-- 下拉加载更多 -->
    <van-list
      v-if="articleList.length > 0"
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
      offset="100"
    >
      <ArticleItem
        v-for="(item, index) in articleList"
        :key="index"
        :item="item"
        :show="false"
        @click.native="articleFn(item)"
      ></ArticleItem>
    </van-list>
  </div>
</template>

<script>
import ArticleItem from '@/components/ArticleItem'
import { searchResultAPI } from '@/api'
export default {
  data () {
    return {
      page: 1, // 搜索结果页码
      articleList: [], // 文章列表数据
      loading: false,
      finished: false
    }
  },
  name: 'SearchResult',
  components: {
    ArticleItem
  },
  async created () {
    this.getResultList() // 页面打开第一次,手动加载第一次
  },
  methods: {
    onLoad () { // 上拉加载更多
      this.page++
      this.getResultList()
    },
    async getResultList () {
      const [, res] = await searchResultAPI({
        q: this.$route.params.keywords, // 路由传参有 query 和 params两种方式
        // 写query里,也是在 url?参数名=值
        // 写params里,也会在url/出现(前提要在路由规则里加 /:参数名)
        page: this.page
      })
      // 判断数据是否加载完毕
      if (res.data.data.results.length === 0) {
        this.finished = true
      } else {
        // 合并2个数组数据
        this.articleList = [...this.articleList, ...res.data.data.results]
        // 重置加载状态
        this.loading = false
      }
    },
    articleFn (item) { // 文章点击跳转具体页面
      this.$router.push({
        path: '/art_detail', // 跳到详情页
        query: { // 问号传参要用query传
          art_id: item.art_id
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.search-result-container {
  padding-top: 46px;
}
</style>
